# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: xguo

import datetime
import dateutil.parser
import getpass
import json
import logging
import pathlib

from absl import app, flags

from coin.experimental.xguo.fruit.base.strategy_sim_base import (
    BaseSimStrategy,
    BaseStrategyConfig,
    convert_book_to_dict,
    convert_trade_to_dict,
)

FLAGS = flags.FLAGS


class FeedDumperConfig(BaseStrategyConfig):
  pass


class FeedWriter(object):
  def __init__(self, trading_date: datetime.datetime, product):
    trading_date_str = trading_date.strftime('%Y%m%d')
    user = getpass.getuser()
    dir_name = f"/remote/iosg/home/{user}/converted_book/{trading_date_str}/"
    dir_path = pathlib.Path(dir_name)
    dir_path.mkdir(parents=True, exist_ok=True)
    self._file = dir_path.joinpath(product.full_symbol).open(mode='w')

  def write(self, dict_data):
    json.dump(dict_data, self._file)
    self._file.write('\n')
    self._file.flush()

  def close(self):
    self._file.close()


class FeedDumper(BaseSimStrategy):
  def __init__(self, config):
    super().__init__(config)
    self._writers = {}
    self._prepare_writers()

  def _prepare_writers(self):
    trading_date = self.strategy_config.sim_config['from_ts']
    for product in self.product_list:
      self._writers[product] = FeedWriter(trading_date, product)

  def on_book(self, book):
    book_dict = convert_book_to_dict(book, level=10, notional_amount=1000)
    self._writers[book.product].write(book_dict)

  def on_trade(self, product, trade_event):
    trade_dict = convert_trade_to_dict(product, trade_event)
    self._writers[product].write(trade_dict)


def main(_):
  if FLAGS.config is None:
    dir_path = pathlib.Path(__file__).parent
    config_file = dir_path.joinpath('feed_dumper_config.yaml')
  else:
    config_file = pathlib.Path(FLAGS.config)

  config = FeedDumperConfig.from_file(config_file)
  from_ts = dateutil.parser.parse(FLAGS.trading_date)
  config.sim_config['from_ts'] = from_ts
  config.sim_config['to_ts'] = from_ts + datetime.timedelta(hours=FLAGS.hours)
  feed_dumper = FeedDumper(config)
  logging.info('Start time: %s', datetime.datetime.now())
  feed_dumper.run()
  logging.info('End time: %s', datetime.datetime.now())


if __name__ == '__main__':
  flags.DEFINE_string('config', None, 'Strategy config file.')

  flags.DEFINE_string('trading_date', None, 'Trading date.')

  flags.DEFINE_integer('hours', 24, 'Hours from trading_date.')

  logging.basicConfig(level='INFO', format='%(levelname)s %(asctime)s %(name)s] %(message)s')
  app.run(main)
